﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using Leeder.Util.Quartz;
using PartsRetrospect.Comm;
using PartsRetrospect.Task;
using PartsRetrospect.Model;
using PartsRetrospect.Business;
using Leeder.Logger;
using PartsRetrospect.Handle;
using System.IO;
using LeederGlobal;

namespace PartsRetrospect.Forms
{
    public partial class FrmHistory : UIPage
    {
        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());
        List<AirbagModel> datas = new List<AirbagModel>();
        AirbagBLL airbagBLL = new AirbagBLL();
        UploadSetBLL uploadSetBLL = new UploadSetBLL();
        CarModelBLL carModelBLL = new CarModelBLL();
        AirbagPositionBLL airbagPositionBLL = new AirbagPositionBLL();
        FtpUploadHandler ftpUploadHandler = new FtpUploadHandler();

        /// <summary>
        /// 车间
        /// </summary>
        string workshop = "1";
        /// <summary>
        /// 计算机编号(配置)
        /// </summary>
        string computerNo = "01";
        /// <summary>
        /// 常量Convert.ToChar(1)
        /// </summary>
        public char chrSeparator = Convert.ToChar(1);
        /// <summary>
        /// 常量Convert.ToChar(10)
        /// </summary>
        public char chrBreak = Convert.ToChar(10);

        List<CarModelModel> carModelList;
        List<AirbagPositionModel> airbagPositionList;

        bool isLoad = true;      //判断窗体是否首次加载
        int pageSize = 30;       //数据表每页默认行数

        public FrmHistory()
        {
            InitializeComponent();
            dgvHistory.AutoGenerateColumns = false;
            //dgvHistory.ReadOnly = true;

            dgvHistory.AddCheckBoxColumn("选择","",80,false);
            dgvHistory.AddColumn("连番", "ManyNo");
            dgvHistory.AddColumn("车身码", "BodyNo");
            dgvHistory.AddColumn("VIN码", "VinCode");
            dgvHistory.AddColumn("气囊码", "AirbagCode");
            dgvHistory.AddColumn("车型", "Model");
            dgvHistory.AddColumn("气囊位置", "PosName");
            dgvHistory.AddColumn("气囊输入模式", "OperateAirbagModel");
            dgvHistory.AddColumn("VIN码输入模式", "OperateCarModel");
            dgvHistory.AddColumn("气囊码扫码时间", "OperateAirbagDate");
            dgvHistory.AddColumn("VIN码扫码时间", "OperateCarDate");
            dgvHistory.AddColumn("上传状态", "UploadState");
        }

        /// <summary>
        /// 数据列表显示文字转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 11)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgvHistory.Rows[e.RowIndex];
                if (row != null)
                {
                    if (row.Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        e.Value = string.Format("{0}",
                          "已上传");
                    }
                    else
                    {
                        e.Value = string.Format("{0}",
                      "未上传");
                    }
                }
            }
            if (e.ColumnIndex == 7 || e.ColumnIndex == 8)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgvHistory.Rows[e.RowIndex];
                if (row != null)
                {
                    if (row.Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        e.Value = string.Format("{0}",
                          "扫码录入");
                    }
                    else if(row.Cells[e.ColumnIndex].Value.ToString() == "2")
                    {
                        e.Value = string.Format("{0}",
                      "人工录入");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "3")
                    {
                        e.Value = string.Format("{0}",
                      "后台更新");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "4")
                    {
                        e.Value = string.Format("{0}",
                      "后台添加");
                    }
                }
            }
        }

        private void FrmHistory_Load(object sender, EventArgs e)
        {
            //设置开始时间为一星期前
            this.dpStartDateVIN.Value = DateTime.Now.AddDays(-7);
            this.dpEndDateVIN.Value = DateTime.Now;

            pageSize = (dgvHistory.Size.Height - 30) / 23;
            datas = airbagBLL.GetModelListByCondition(dpStartDateVIN.Value, dpEndDateVIN.Value);

            //设置分页控件总数
            uiPagination1.TotalCount = datas.Count;

            //设置分页控件每页数量
            uiPagination1.PageSize = pageSize;

            uiPagination1_PageChanged(null, null, 1, pageSize);
            //如果窗体已经加载过则不重新加载
            if (!isLoad)
                return;
            isLoad = false;
            uiPagination1.Style = UIStyle.Blue;
            carModelList = carModelBLL.GetModelAll();
            airbagPositionList = airbagPositionBLL.GetModelAll();

            carModelList.Insert(0,new CarModelModel {CarModelCode = "--ALL--"});
            airbagPositionList.Insert(0, new AirbagPositionModel { AiebagPosition = "--全部--" });

            cbModel.DataSource = carModelList;
            cbModel.DisplayMember = "CarModelCode";
            cbModel.ValueMember = "CarModelCode";
            cbPosName.DataSource = airbagPositionList;
            cbPosName.DisplayMember = "AiebagPosition";
            cbPosName.ValueMember = "AiebagPosition";

            cbOperateAirbagModel.SelectedIndex = 0;
            cbOperateCarModel.SelectedIndex = 0;
            cbPosName.SelectedIndex = 0;
            cbModel.SelectedIndex = 0;
            cbUploadState.SelectedIndex = 0;
        }

        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            //一般通过ORM的分页去取数据来填充
            //pageIndex：第几页，和界面对应，从1开始，取数据可能要用pageIndex - 1
            //count：单页数据量，也就是PageSize值
            List<AirbagModel> data = new List<AirbagModel>();
            for (int i = (pageIndex - 1) * count; i < (pageIndex - 1) * count + count; i++)
            {
                if (i >= datas.Count) continue;
                data.Add(datas[i]);
            }
            dgvHistory.DataSource = data;
            dgvHistory.Refresh();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            Upload();
            Search();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission != 0)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }
            Delete();
            Search();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            //Export();
            ExportXLSD2(dgvHistory);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            InputBarCode("",2);
            Search();
        }

        private void cbDataTimeVIN_CheckedChanged(object sender, EventArgs e)
        {
            if(cbDataTimeVIN.Checked)
            {
                dpStartDateVIN.Enabled = true;
                dpEndDateVIN.Enabled = true;
            }
            else
            {
                dpStartDateVIN.Enabled = false;
                dpEndDateVIN.Enabled = false;
            }
        }

        private void cbDataTimeAB_CheckedChanged(object sender, EventArgs e)
        {
            if (cbDataTimeAB.Checked)
            {
                dpStartDateAB.Enabled = true;
                dpEndDateAB.Enabled = true;
            }
            else
            {
                dpStartDateAB.Enabled = false;
                dpEndDateAB.Enabled = false;
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        private void Search()
        {
            DateTime? startDateVIN = null;
            DateTime? endDateVIN = null;
            DateTime? startDateAB = null;
            DateTime? endDateAB = null;
            if (cbDataTimeVIN.Checked)
            {
                startDateVIN = dpStartDateVIN.Value;
                endDateVIN = dpEndDateVIN.Value;
            }
            if (cbDataTimeAB.Checked)
            {
                startDateAB = dpStartDateAB.Value;
                endDateAB = dpEndDateAB.Value;
            }
            datas = airbagBLL.GetModelListByCondition(txtVinCode.Text, txtAirbagCode.Text, txtBodyNo.Text, txtManyNo.Text, cbOperateCarModel.SelectedIndex, cbOperateAirbagModel.SelectedIndex, cbPosName.SelectedValue.ToString(), cbModel.SelectedValue.ToString(), cbUploadState.SelectedIndex - 1, startDateVIN, endDateVIN, startDateAB, endDateAB);
            uiPagination1.TotalCount = datas.Count;
            uiPagination1_PageChanged(null, null, 1, pageSize);
        }

        /// <summary>
        /// 删除
        /// </summary>
        private void Delete()
        {
            List<AirbagModel> list = new List<AirbagModel>();
            foreach (DataGridViewRow row in dgvHistory.Rows)
            {
                if ((bool)row.Cells[0].EditedFormattedValue == true)
                {
                    var airbag = dgvHistory.Rows[row.Index].DataBoundItem as AirbagModel;
                    airbag.IsPhantom = true;
                    list.Add(airbag);
                }
            }
            if (list.Count == 0)
            {
                UIMessageBox.ShowError("请先勾选数据！");
                return;
            }

            if (!UIMessageDialog.ShowMessageDialog("你确定要删除气囊数据吗？", UILocalize.AskTitle, true, UIStyle.Orange, true, Frame?.TopMost ?? false))
            {
                return;
            }

            if (airbagBLL.UpdateList(list).IsSuccess)
            {
                UIMessageTip.ShowOk("删除成功！");
            }
            else
            {
                UIMessageBox.ShowError("删除失败！");
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        private void Upload()
        {
            string errMesg = "";
            List<AirbagModel> list = new List<AirbagModel>();
            foreach (DataGridViewRow row in dgvHistory.Rows)
            {
                if (((bool)row.Cells[0].EditedFormattedValue) == true)
                {
                    var airbag = dgvHistory.Rows[row.Index].DataBoundItem as AirbagModel;
                    if (airbag.UploadState == 1)
                    {
                        if (!UIMessageDialog.ShowMessageDialog("气囊(" + airbag.AirbagCode + ")已经上传，确定要再次上传吗？", UILocalize.AskTitle, true, UIStyle.Orange, true, Frame?.TopMost ?? false))
                        {
                            continue;
                        }
                    }
                    list.Add(airbag);
                }
            }
            if (list.Count == 0)
            {
                UIMessageBox.ShowError("请先勾选数据！");
                return;
            }
            UploadSetModel model = uploadSetBLL.GetModel();
            ftpUploadHandler.SFtpIp = model.IP;
            ftpUploadHandler.SFtpPort = model.Port;
            ftpUploadHandler.SFtpUser = model.UserName;
            ftpUploadHandler.SFtpPwd = model.Password;
            ftpUploadHandler.UploadFilePath = model.UploadPath;
            ftpUploadHandler.workshop = GolbalVariable.WorkShopSet.WorkShopNo.ToString();
            ftpUploadHandler.computerNo = GolbalVariable.WorkShopSet.ComputerNo;
            if (ftpUploadHandler.UploadData(list, ref errMesg))
            {
                LogObj.Info("气囊数据手动上传成功，上传数量:" + 1);
                if (airbagBLL.UpdateUploadState(list))
                {
                    LogObj.Info("气囊数据上传状态更新成功！");
                    UIMessageTip.ShowOk("上传成功！");
                }
                else
                {
                    LogObj.Info("气囊数据上传状态更新失败！");
                    UIMessageBox.ShowError("气囊数据上传状态更新失败！");
                }
            }
            else
            {
                LogObj.Info("气囊数据上传失败，失败原因:" + errMesg);
                UIMessageBox.ShowError("气囊数据上传失败，失败原因:" + errMesg);
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="datagridview1"></param>
        public void ExportXLSD2(DataGridView datagridview)
        {
            SaveFileDialog savefiledialog1 = new SaveFileDialog();
            StreamWriter sw = null;
            FileStream FS = null;
            if (datagridview.Rows.Count > 0)
            {
                string MyFileName = "", FileName = "";
                savefiledialog1.AddExtension = true;// '如果用户忘记添加扩展名，将自动加上
                savefiledialog1.DefaultExt = "txt";//'默认扩展名
                savefiledialog1.Filter = "文本文件(*.txt)|*.txt";
                savefiledialog1.Title = "文件保存到";
                if (savefiledialog1.ShowDialog() == DialogResult.OK)
                {
                    FileName = savefiledialog1.FileName;
                }
                if (string.IsNullOrEmpty(FileName)) return;
                MyFileName = FileName.Substring(FileName.Length - 4, 4);
                if (MyFileName == ".txt" || MyFileName == ".TXT")
                {
                    FS = new FileStream(FileName, FileMode.Create);
                    sw = new StreamWriter(FS, System.Text.Encoding.Default);
                    sw.WriteLine("\t" + FileName + "\t" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"));
                    string str = "";
                    for (int iu = 1; iu < datagridview.Columns.Count; iu++)
                    {
                        str = datagridview.Columns[iu].HeaderText;
                        sw.Write(str + "\t");
                    }
                    sw.Write("\r\n");
                }

                for (int j = 0; j < datagridview.Rows.Count; j++)
                {
                    for (int k = 1; k < datagridview.Columns.Count; k++)
                    {
                        string strRow = ConversionFun.ObjToStr(datagridview[k, j].Value);
                        sw.Write(strRow + "\t");
                    }
                    sw.Write("\r\n");
                }
                sw.Close();
                FS.Close();
            }
            else
            {
                MessageBox.Show("没有记录不能导出数据！", "消息框", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        private void Export()
        {
            List<AirbagModel> list = new List<AirbagModel>();
            foreach (DataGridViewRow row in dgvHistory.Rows)
            {
                if ((bool)row.Cells[0].EditedFormattedValue == true)
                {
                    var airbag = dgvHistory.Rows[row.Index].DataBoundItem as AirbagModel;
                    airbag.IsPhantom = true;
                    list.Add(airbag);
                }
            }
            if (list.Count == 0)
            {
                UIMessageBox.ShowError("请先勾选数据！");
                return;
            }
            FolderBrowserDialog myDialog = new FolderBrowserDialog();
            myDialog.ShowNewFolderButton = false;
            myDialog.Description = "选择你要设置的文件夹或目录 ";
            string path = string.Empty;
            if (myDialog.ShowDialog() == DialogResult.OK)
                path = myDialog.SelectedPath;
            else
            {
                myDialog.Dispose();
                return;
            }
            path += "\\气囊记录.txt";
            AddHeader(path);
            AddDetail(list, path);
            UIMessageBox.Show("数据导出完成！");
        }

        /// <summary>
        /// 输入条码
        /// </summary>
        /// <param name="barCode">条码</param>
        /// <param name="index">条码类型(1车辆条码；2气囊条码；)</param>
        /// <param name="updateAirbagPosition">修改气囊位置(新增时默认为空，修改时要传入气囊位置)</param>
        private void InputBarCode(string barCode = "", int index = 1, string updateAirbagPosition = null)
        {
            if(dgvHistory.RowCount == 0)
            {
                UIMessageBox.ShowError("请先选择要更新的数据");
                return;
            }
            var model = dgvHistory.CurrentRow.DataBoundItem as AirbagModel;
            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            if (index == 1)
                option.Text = "请输入长度为" + BarCodeConfigModel.barCarLength + "的条码";
            else
                option.Text = "请输入长度为" + BarCodeConfigModel.barAirbagL + "的条码";
            option.AddText("BarCode", "条码", barCode, true);
            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();
            if (frm.IsOK)
            {
                string errMesg = "";
                barCode = frm["BarCode"].ToString();
                if (index == 1)
                {
                    if (!airbagBLL.CarBarEnter(barCode, false, ref errMesg))
                    {
                        UIMessageBox.ShowError(errMesg);
                        InputBarCode(barCode, index);
                    }
                }
                else
                {
                    string airbagPositoin= "";
                    string endFlag = "";
                    if (!airbagBLL.CheckAirbagBar(false, barCode, model.ModelCode, model.VType, ref airbagPositoin, ref endFlag, ref errMesg))
                    {
                        UIMessageBox.ShowError(errMesg);
                        InputBarCode(barCode, index);
                    }
                    else
                    {
                        model.AirbagCode = barCode;
                        model.PosName = airbagPositoin;
                        model.BarCodeEndChar = endFlag;
                        model.OperateAirbagDate = DateTime.Now;
                        model.UploadState = 0;
                        model.OperateAirbagModel = 3;
                        if (airbagBLL.Update(model).IsSuccess)
                        {
                            UIMessageBox.ShowSuccess("气囊更新成功！");
                        }
                        else
                        {
                            UIMessageBox.ShowError("气囊更新失败！");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 生成带有固定报文头的TXT文件
        /// </summary>
        /// <param name="strPath">文件路径</param>
        public void AddHeader(string strPath)
        {
            string[] col = new string[16];
            string strHander = "#";
            col[0] = "VIN"; col[1] = "Airbag"; col[2] = "BodyNo"; col[3] = "ManyNO"; col[4] = "Model"; col[5] = "PosName"; col[6] = "VinMode"; col[7] = "VinTime";
            col[8] = "AirbagMode"; col[9] = "AirbagTime"; col[10] = "Station"; col[11] = "Factory"; col[12] = "Operator"; col[13] = "Valid"; col[14] = "InvalidTime"; col[15] = "InvalidOperator";
            for (int h = 0; h < 16; h++)
            {
                if (h < 15)
                    strHander = strHander + col[h] + chrSeparator;
                else
                    strHander = strHander + col[h];
            }
            strHander = strHander + chrSeparator + "OPERATE_TYPE" + chrSeparator + "EXTRACT_TIME" + chrBreak;
            WriteTxt(strPath, strHander);
        }

        /// <summary>
        /// 往TXT文件里写入报文
        /// </summary>
        /// <param name="modelList">数据体集合</param>
        /// <param name="strPath">文件路径</param>
        public void AddDetail(List<AirbagModel> modelList, string strPath)
        {
            string strcontent = "";
            foreach (var model in modelList)
            {
                string vin = model.VinCode;
                string Airbag = model.AirbagCode;
                string UploadType = model.UploadType;

                if (string.IsNullOrWhiteSpace(vin + Airbag)) continue;

                strcontent += ObjToStr(model.VinCode, " ") + chrSeparator;                         //VIN码                  
                strcontent += ObjToStr(model.AirbagCode, " ") + chrSeparator;                     //气囊码
                strcontent += ObjToStr(model.BodyNo, " ") + chrSeparator;                         //车身码
                strcontent += ObjToStr(model.ManyNo, " ") + chrSeparator;                         //连番号
                strcontent += ObjToStr(model.Model, " ") + chrSeparator;                          //车型英文名称
                strcontent += ObjToStr(model.PosName, " ") + chrSeparator;                        //气囊位置
                strcontent += ObjToStr(model.OperateCarModel, " ") + chrSeparator;                //VIN码录入模式
                strcontent += ObjToStr(model.OperateCarDate, " ") + chrSeparator;                 //VIN码录入时间
                strcontent += ObjToStr(model.OperateAirbagModel, " ") + chrSeparator;             //气囊录入模式
                strcontent += ObjToStr(model.OperateAirbagDate, " ") + chrSeparator;               //气囊录入时间
                strcontent += ObjToStr(model.Station, " ") + chrSeparator;                         //位置
                strcontent += ObjToStr(model.Factory, " ") + chrSeparator;                         //车间编号
                strcontent += ObjToStr(model.Operator, " ") + chrSeparator;                        //操作人编号
                strcontent += ObjToStr(model.Valid, " ") + chrSeparator;                           //无效
                strcontent += ObjToStr(model.InvalidTime, " ") + chrSeparator;                     //无效时间
                strcontent += ObjToStr(model.InvalidOperator, " ") + chrSeparator;                 //无效操作人编号
                strcontent += ObjToStr(model.UploadType, " ") + chrSeparator;                      //上传类型
                strcontent += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff");                 //时间
                strcontent += chrBreak;
            }
            strcontent += Convert.ToChar(13);
            WriteTxt(strPath, strcontent);
        }

        /// <summary>
        /// 生成TXT文件
        /// </summary>
        /// <param name="strPath">生成路径</param>
        /// <param name="txt">文本内容</param>
        public void WriteTxt(string strPath, string txt)
        {
            StreamWriter sw = new StreamWriter(strPath, true, new UTF8Encoding(false));
            sw.Write(txt);
            sw.Close();
        }

        public string ObjToStr(object obj, string dfault = "")
        {
            if (obj == DBNull.Value) return dfault;
            if (obj == null) return dfault;
            string rts = obj.ToString();
            if (string.IsNullOrWhiteSpace(rts)) return dfault;
            return obj.ToString();
        }

        private void dgvCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            //dgvHistory.ClearSelection();
            if (dgvCheckBox.Checked)
            {
                for (int i = 0; i < dgvHistory.Rows.Count; i++)
                {
                        dgvHistory.Rows[i].Cells[0].Value = "True";
                }
            }
            else
            {
                for (int i = 0; i < dgvHistory.Rows.Count; i++)
                {
                    dgvHistory.Rows[i].Cells[0].Value = "False";
                }
            }
            dgvHistory.EndEdit();
            //dgvHistory.Refresh();
        }
    }
}
